﻿
using HalconDotNet;
using HslCommunication.BasicFramework;
using Lmi3d.GoSdk.Messages;
using NDK.Module.BLL;
using NDK.Module.Model;
using NDK.Motion.Sys;
using NDK.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

namespace NDK.Module.StationLogic
{
    public class DataProcess
    {
        public static DataProcess Instance = new DataProcess();

        public ConcurrentDictionary<string, MeasureProduct> DatasDic;

        public SunWayMes mes = new SunWayMes();

        public ConcurrentQueue<int> DataResult;

        public string result1;

        public DataProcess()
        {
            Thread thread1 = new Thread(() => ThreadDataProcess())
            {
                IsBackground = true
            };
            thread1.Start();
        }

        public void ThreadDataProcess()
        {
            while (true)
            {
                try
                {
                    if (Station_PPG测量.Instance.PPGVaueQueue != null)
                    {
                        if (Station_PPG测量.Instance.PPGVaueQueue.Count > 0)
                        {
                            Station_转盘一穴.Instance.ValueQueue.TryDequeue(out var queue);
                            Station_下置激光.Instance.QueueSN.TryDequeue(out var TestSn);
                            Station_PPG测量.Instance.PPGVaueQueue.TryDequeue(out var MP);
                            Station_产品扫码.Instance.QueueSN.TryDequeue(out string SN);

                            SaveImageAsync(SN);
                            DatasDic.TryGetValue(TestSn, out var qwe);
                            DatasDic.TryRemove(TestSn, out var data);
                            MP.SN = SN;
                            MP.TestStart = queue.TestStart;
                            MP.TurnTableHole = data.TurnTableHole;
                            MP.MeasureData.AddRange(data.MeasureData);
                            int result = 3;
                            if(SN != "CheckNG")
                            {
                                if (!Common.BP_屏蔽算法)
                                {
                                    var re = ProcessData.PrcessData(MP);
                                    switch (re)
                                    {
                                        case JUDGEMENT_RESULT.OK:
                                            result = 1;
                                            break;
                                        case JUDGEMENT_RESULT.NG:
                                            result = 2;
                                            break;
                                    }
                                }
                            }
                            DataResult.Enqueue(result);
                        }
                    }
                }
                catch (Exception)
                {

                }
                Thread.Sleep(100);
            }
        }


        protected readonly object TomLock = new object();
        private int i = 0;
        public void SaveImageAsync(string SN)
        {
            Task.Run(() =>
            {
                try
                {
                    string FixLocalPath = string.Empty;
                    MeasureImage image二穴, image七穴, image下;
                    lock (TomLock)
                    {
                        DateTime DT = DateTime.Now;
                        Station_转盘二穴.Instance.QueueImage.TryDequeue(out image二穴);
                        Station_转盘七穴.Instance.QueueImage.TryDequeue(out image七穴);
                        Station_下置激光.Instance.QueueImage.TryDequeue(out image下);
                        i++;
                        FixLocalPath = $"{Common.picSavePath}\\{DT:yyyy-MM-dd}\\{Common.CurProType}\\{SN}_{DT:yyyyMMddHHmmss}_Hole{image二穴.Hole}_{i}";
                    }
                    if(SN != "CheckNG")
                    {
                        if (!FileUtils.IsExistDirectory(FixLocalPath))
                        {
                            FileUtils.CreateDirectory(FixLocalPath);
                        }
                        HOperatorSet.WriteImage(image二穴.Images[0].Item2, "bmp", 0, $"{FixLocalPath}\\{image二穴.Images[0].Item1}");
                        HOperatorSet.WriteImage(image下.Images[0].Item2, "tiff", 0, $"{FixLocalPath}\\{image下.Images[0].Item1}");
                        foreach (var item in image七穴.Images)
                        {
                            HOperatorSet.WriteImage(item.Item2, item.Item1.Contains("CCD") ? "bmp" : "tiff", 0, $"{FixLocalPath}\\{item.Item1}");
                        }
                    }
                }
                catch (Exception ex)
                {

                }
            });
        }

        public void SaveImageAsync1(string SN)
        {
            Task.Run(() =>
            {
                try
                {
                    string FixLocalPath = string.Empty;
                    MeasureImage image二穴, image七穴, image下;
                    lock (TomLock)
                    {
                        DateTime DT = DateTime.Now;
                        Station_转盘二穴.Instance.QueueImage.TryDequeue(out image二穴);
                        Station_转盘七穴.Instance.QueueImage.TryDequeue(out image七穴);
                        Station_下置激光.Instance.QueueImage.TryDequeue(out image下);
                        i++;
                        FixLocalPath = $"{Common.picSavePath}\\{DT:yyyy-MM-dd}\\{Common.CurProType}\\{SN}_{DT:yyyyMMddHHmmss}_Hole{image二穴.Hole}_{i}";
                    }
                    if (SN != "CheckNG")
                    {
                        if (!FileUtils.IsExistDirectory(FixLocalPath))
                        {
                            FileUtils.CreateDirectory(FixLocalPath);
                        }
                        HOperatorSet.WriteImage(image二穴.Images[0].Item2, "jpg", 0, $"{FixLocalPath}\\{image二穴.Images[0].Item1}");
                        HOperatorSet.WriteImage(image下.Images[0].Item2, "tiff.lzw", 0, $"{FixLocalPath}\\{image下.Images[0].Item1}");
                        foreach (var item in image七穴.Images)
                        {
                            HOperatorSet.WriteImage(item.Item2, item.Item1.Contains("CCD") ? "jpg" : "tiff.lzw", 0, $"{FixLocalPath}\\{item.Item1}");
                        }
                    }
                }
                catch (Exception ex)
                {

                }
            });
        }

        public Task VisionProcessAsync(string flowName, string outDataName, int HoleId, string Sn, params (string, HImage)[] images)
        {
            return Task.Run(() =>
                   {
                       try
                       {
                           if (!Common.BP_屏蔽算法 && !Common.IsEmptyModel)
                           {
                               VisionPlatform.VisionManager.Engine eng = null;
                               eng = new VisionPlatform.VisionManager.Engine(flowName);
                               foreach (var item in images)
                               {
                                   eng.SetInputImage(item.Item1, item.Item2);
                               }
                               eng.SetInputNumber("PanNum", HoleId - 1);
                               eng.SetInputNumber("IsType604", Common.BP_Is604 ? 1 : 0);
                               eng.SetInputString("ID", Sn);
                               eng.ActionFun();
                               string strResult = eng.GetOutputString(outDataName);
                               List<DataItem> listDataItems = new List<DataItem>();
                               if (strResult != "")
                               {
                                   Dictionary<string, double> dic = new Dictionary<string, double>();
                                   dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult);

                                   foreach (var item in dic)
                                   {
                                       DataItem FAI = new DataItem
                                       {
                                           Name = item.Key,
                                           Value = item.Value,
                                           Position = 0
                                       };
                                       listDataItems.Add(FAI);
                                   }
                                   if (!DatasDic.ContainsKey(Sn))
                                   {
                                       DatasDic.TryAdd(Sn, new MeasureProduct() { TurnTableHole = HoleId, MeasureData = new List<DataItem>() });
                                   }
                                   DatasDic[Sn].MeasureData.AddRange(listDataItems);
                                   if (Common.GRR循环模式 && flowName == Station_下置激光.Instance.VisionFlowName)
                                   {
                                       SaveImageAsync(Sn);
                                       DatasDic.TryRemove(Sn, out var data);
                                       data.SN = Sn;
                                       ProcessData.PrcessData(data);
                                   }
                               }
                           }
                       }
                       catch (Exception ex)
                       {
                           Common.AppendUiLog.Log($"{flowName}算法流程异常{ex}", BZ.Logger.LogType.Error);
                       }
                   });
        }

        public void VisionProcess(string flowName, string outDataName, int HoleId, string Sn, params (string, HImage)[] images)
        {
            try
            {
                if (!Common.BP_屏蔽算法 && !Common.IsEmptyModel)
                {
                    VisionPlatform.VisionManager.Engine eng = null;
                    eng = new VisionPlatform.VisionManager.Engine(flowName);
                    foreach (var item in images)
                    {
                        eng.SetInputImage(item.Item1, item.Item2);
                    }
                    eng.SetInputNumber("PanNum", HoleId - 1);
                    eng.SetInputNumber("IsType604", Common.BP_Is604 ? 1 : 0);
                    eng.SetInputString("ID", Sn);
                    eng.ActionFun();
                    string strResult = eng.GetOutputString(outDataName);
                    List<DataItem> listDataItems = new List<DataItem>();
                    if (strResult != "")
                    {
                        Dictionary<string, double> dic = new Dictionary<string, double>();
                        dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult);

                        foreach (var item in dic)
                        {
                            DataItem FAI = new DataItem
                            {
                                Name = item.Key,
                                Value = item.Value,
                                Position = 0
                            };
                            listDataItems.Add(FAI);
                        }
                        if (!DatasDic.ContainsKey(Sn))
                        {
                            DatasDic.TryAdd(Sn, new MeasureProduct() { TurnTableHole = HoleId, MeasureData = new List<DataItem>() });
                        }
                        DatasDic[Sn].MeasureData.AddRange(listDataItems);
                    }
                }
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"{flowName}算法流程异常{ex}", BZ.Logger.LogType.Error);
            }
        }
    }
}